package com.xgpro.pc.archives.service.impl;



import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xgpro.common.enums.ResultCodeEnum;
import com.xgpro.common.exceptions.BusinessRuntimeException;
import com.xgpro.common.results.ResponseResult;
import com.xgpro.common.utils.*;
import com.xgpro.domain.archives.dto.*;
import com.xgpro.domain.archives.entity.*;
import com.xgpro.domain.archives.vo.Archives;
import com.xgpro.domain.talentintroduction.entity.User;
import com.xgpro.mapper.archives.*;
import com.xgpro.mapper.talentintroduction.UserMapper;
import com.xgpro.pc.archives.service.PcArchivesService;
import com.xgpro.pc.rolemanage.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
@Transactional(readOnly = false)
public class PcArchivesServiceImpl implements PcArchivesService {

    private static  List<List<Object>> errorData;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ArchivesMapper archivesMapper;

    @Resource
    private RankApprovalMapper rankApprovalMapper;

    @Resource
    private PatentMapper patentMapper;

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private PerForManceMapper perForManceMapper;

    @Resource
    private SixSigmaMapper sigmaMapper;

    @Resource
    private UserService userService;

    @Resource
    private SendMsgUtil  msgUtil;

    @Resource
    private DDMsgUtil  ddMsgUtil;

    @Override
    public ResponseResult getApproval(String rankName, String deptName, Integer status,Integer pageNum,Integer pageSize) {
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum=1;
        }
        if(ObjectUtils.isEmpty(pageSize)){
            pageSize=10;
        }
        List<RankApproval> rankApprovals = new ArrayList<>();
        if(ObjectUtils.isEmpty(rankName) && ObjectUtils.isEmpty(deptName) && ObjectUtils.isEmpty(status)){
            PageHelper.startPage(pageNum,pageSize);
            rankApprovals =rankApprovalMapper.selectBy(rankName,deptName,status);
        }else {
            PageHelper.startPage(pageNum,pageSize);
            rankApprovals = rankApprovalMapper.selectBy(rankName,deptName,status);
        }
        PageInfo pageInfo=new PageInfo(rankApprovals);
        Map map = new HashMap<>();
        map.put("pageNum", pageInfo.getPageNum());
        map.put("pageSize", pageInfo.getPageSize());
        map.put("Pages", pageInfo.getPages());
        map.put("total", pageInfo.getTotal());
        map.put("rankApprovals", pageInfo.getList());
        return ResponseResult.ok(map);
    }

    @Override
    public ResponseResult getApprovalInfo(Integer id) {
        try {
            if(ObjectUtils.isEmpty(id)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            RankApproval rankApproval = rankApprovalMapper.selectByPrimaryKey(id);
            Approvals approvals=new Approvals();
            if(!ObjectUtils.isEmpty(rankApproval)){
                BeanUtils.copyProperties(rankApproval,approvals);
                if(!ObjectUtils.isEmpty(rankApproval.getHiredDate())){
                    approvals.setHiredDate(rankApproval.getHiredDate());
                }
                Integer userId = rankApproval.getUserId();
                if(!ObjectUtils.isEmpty(userId)){
                    User user = userMapper.selectByPrimaryKey(userId);
                    if(!ObjectUtils.isEmpty(user) && !ObjectUtils.isEmpty(user.getPhoto())){
                        approvals.setPhoto(user.getPhoto());
                    }
                }
            }
            return ResponseResult.ok(approvals);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult updateApproval(ApprovalInfo approvalInfo) {
        try {
            if(ObjectUtils.isEmpty(approvalInfo)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            List<Body> bodys = approvalInfo.getBody();
            if(CollectionUtils.isEmpty(bodys)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            for (Body body : bodys) {
                Integer id = body.getId();
                Integer status = body.getStatus();
                Integer userId = body.getUserId();
                Integer rankId = body.getRankId();
                String msg = body.getMsg();
                if(!ObjectUtils.isEmpty(id) && !ObjectUtils.isEmpty(status) &&
                        !ObjectUtils.isEmpty(userId) && !ObjectUtils.isEmpty(rankId)){
                    RankApproval rankApproval = new RankApproval();
                    rankApproval.setId(id);
                    rankApproval.setStatus(status);
                    rankApproval.setUpdateTime(new Date());
                    if(!ObjectUtils.isEmpty(msg)){
                      rankApproval.setMsg(msg);
                    }
                    int a = rankApprovalMapper.updateByPrimaryKeySelective(rankApproval);
                    if (a <= 0) {
                        throw new BusinessRuntimeException(ResultCodeEnum.APPROVAL_FAIL.getCode(), ResultCodeEnum.APPROVAL_FAIL.getMessage());
                    }
                    if(status==2){
                        User user=new User();
                        user.setId(userId);
                        user.setRankId(rankId);
                        user.setRankUpdate(new Date());
                        int i = userMapper.updateByPrimaryKeySelective(user);
                        if (i <= 0) {
                            throw new BusinessRuntimeException(ResultCodeEnum.UPDATE_FAIL.getCode(), ResultCodeEnum.UPDATE_FAIL.getMessage());
                        }
                        if(ObjectUtils.isEmpty(msg)){
                            msg=ReadPropertiesUtil.readUrl("rank_success");
                        }
                        msgUtil.sendMsg("审核通过",msg,userId);
                        List<Integer> userList = new ArrayList<>();
                        userList.add(userId);
                        String s = userService.selectAllUserId(userList);
                        ddMsgUtil.sendMsg(s,msg);
                    }else if(status==3){
                        if(ObjectUtils.isEmpty(msg)){
                            msg=ReadPropertiesUtil.readUrl("rank_fail");
                        }
                        msgUtil.sendMsg("审核驳回",msg,userId);
                        List<Integer> userList = new ArrayList<>();
                        userList.add(userId);
                        String s = userService.selectAllUserId(userList);
                        ddMsgUtil.sendMsg(s,msg);
                    }
                }else {
                    throw new BusinessRuntimeException(ResultCodeEnum.INCOMPLETE_PROMOTION_INFORMATION.getCode(),ResultCodeEnum.INCOMPLETE_PROMOTION_INFORMATION.getMessage());
                }
            }
            return ResponseResult.ok();
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.failure(ResultCodeEnum.INCOMPLETE_PROMOTION_INFORMATION.getCode(),ResultCodeEnum.INCOMPLETE_PROMOTION_INFORMATION.getMessage());
        }
    }

    @Override
    public ResponseResult deleteApproval(List<Integer> ids) {
        try {
            if(CollectionUtils.isEmpty(ids)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            List<Integer> list = rankApprovalMapper.getStatus(ids);
            int i =-1;
            if(!CollectionUtils.isEmpty(list)){
                if(list.contains(1)){
                    throw new BusinessRuntimeException(ResultCodeEnum.NOT_APPROVED.getCode(),ResultCodeEnum.NOT_APPROVED.getMessage());
                }
                i= rankApprovalMapper.beletes(ids);
                if(i<=0){
                    throw new BusinessRuntimeException(ResultCodeEnum.DELETE_FAIL.getCode(),ResultCodeEnum.DELETE_FAIL.getMessage());
                }
            }

            return ResponseResult.ok(i);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult getRankName() {
        List<String> rankNames = archivesMapper.getRankName();
        List<String> diff=new ArrayList<>();
        for (String rankName : rankNames) {
            if(diff.contains(rankName)){
                continue;
            }else {
                diff.add(rankName);
            }
        }
        List<String> list = sortList(diff);
        return ResponseResult.ok(list);
    }

    @Override
    public ResponseResult getDeptName() {
        List<String> deptmentNames = archivesMapper.getDeptmentName();
        List<String> diff=new ArrayList<>();
        for (String rankName : deptmentNames) {
            if(diff.contains(rankName)){
                continue;
            }else {
                diff.add(rankName);
            }
        }
        List<String> list = sortList(diff);
        return ResponseResult.ok(list);
    }

    @Override
    public ResponseResult getArchives(String name, String deptName, Integer eduKind, Integer pageNum, Integer pageSize) {
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum=1;
        }
        if(ObjectUtils.isEmpty(pageSize)){
            pageSize=10;
        }
        PageHelper.startPage(pageNum,pageSize);
        List<Archives> archives = archivesMapper.getArchives(name, deptName, eduKind);
        PageInfo pageInfo=new PageInfo(archives);
        Map map = new HashMap<>();
        map.put("pageNum", pageInfo.getPageNum());
        map.put("pageSize", pageInfo.getPageSize());
        map.put("Pages", pageInfo.getPages());
        map.put("total", pageInfo.getTotal());
        map.put("rankApprovals", pageInfo.getList());
        return ResponseResult.ok(map);
    }

    @Override
    public ResponseResult getUser(Integer userId) {
        try {
            if(ObjectUtils.isEmpty(userId)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            Archives archives = getDetails(userId);
            List<PerForMance> per = archivesMapper.getPer(userId);
            Map map = getTimes(userId);
            archives.setUserId(userId);
            archives.setClassTime((Integer) map.get("classTime"));
            archives.setAttendanceTime((Integer) map.get("attendanceTime"));
            archives.setPerForMances(per);
            return ResponseResult.ok(archives);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }

    }

    @Override
    public ResponseResult getPanent(Integer userId,String name,Integer type, Integer pageNum, Integer pageSize) {
        try {
            if(ObjectUtils.isEmpty(pageNum)){
                pageNum=1;
            }
            if(ObjectUtils.isEmpty(pageSize)){
                pageSize=10;
            }
            if(ObjectUtils.isEmpty(userId)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            PageHelper.startPage(pageNum,pageSize);
            List<Patentt> patentts = patentMapper.getPanentt(userId, name, type);
            PageInfo pageInfo=new PageInfo(patentts);
            Map map = new HashMap<>();
            map.put("pageNum", pageInfo.getPageNum());
            map.put("pageSize", pageInfo.getPageSize());
            map.put("Pages", pageInfo.getPages());
            map.put("total", pageInfo.getTotal());
            map.put("rankApprovals", pageInfo.getList());
            return ResponseResult.ok(map);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult getProject(Integer userId,String name, Integer type, Integer pageNum, Integer pageSize) {
        try {
            if(ObjectUtils.isEmpty(pageNum)){
                pageNum=1;
            }
            if(ObjectUtils.isEmpty(pageSize)){
                pageSize=10;
            }
            if(ObjectUtils.isEmpty(userId)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            PageHelper.startPage(pageNum,pageSize);
            List<Projectt> projects  = projectMapper.getProject(userId,type,name);
            PageInfo pageInfo=new PageInfo(projects);
            Map map = new HashMap<>();
            map.put("pageNum", pageInfo.getPageNum());
            map.put("pageSize", pageInfo.getPageSize());
            map.put("Pages", pageInfo.getPages());
            map.put("total", pageInfo.getTotal());
            map.put("rankApprovals", pageInfo.getList());
            return ResponseResult.ok(map);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult deleteUser(List<Integer> ids) {
        try {
            if(CollectionUtils.isEmpty(ids)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            int i = userMapper.batchDeletes(ids);
            if(i<=0){
                throw new BusinessRuntimeException(ResultCodeEnum.DELETE_FAIL.getCode(),ResultCodeEnum.DELETE_FAIL.getMessage());
            }
            patentMapper.beletes(ids);
            projectMapper.beletes(ids);
            perForManceMapper.beletes(ids);
            return ResponseResult.ok(i);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult deletePatent(List<Integer> ids) {
        try {
            if(CollectionUtils.isEmpty(ids)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            int i =patentMapper.batchDeletes(ids);
            if(i<=0){
                throw new BusinessRuntimeException(ResultCodeEnum.DELETE_FAIL.getCode(),ResultCodeEnum.DELETE_FAIL.getMessage());
            }
            return ResponseResult.ok(i);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }


    @Override
    public ResponseResult deleteProject(List<Integer> ids) {
        try {
            if(CollectionUtils.isEmpty(ids)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            int i =projectMapper.batchDeletes(ids);
            if(i<=0){
                throw new BusinessRuntimeException(ResultCodeEnum.DELETE_FAIL.getCode(),ResultCodeEnum.DELETE_FAIL.getMessage());
            }
            return ResponseResult.ok(i);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult addPatent(Patent patent) {
        try {
            if(ObjectUtils.isEmpty(patent)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            int i = patentMapper.insertSelective(patent);
            if(i==0){
                throw new BusinessRuntimeException(ResultCodeEnum.ADD_FAILE.getCode(),ResultCodeEnum.ADD_FAILE.getMessage());
            }
            return ResponseResult.ok(i);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult addProject(Project project) {
        try {
            if(ObjectUtils.isEmpty(project)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            int a = projectMapper.insertSelective(project);
            if(a==0){
                throw new BusinessRuntimeException(ResultCodeEnum.ADD_FAILE.getCode(),ResultCodeEnum.ADD_FAILE.getMessage());
            }
            return ResponseResult.ok(a);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult updateProject(Project project) {
        try {
            if(ObjectUtils.isEmpty(project)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            int a = projectMapper.updateByPrimaryKeySelective(project);
            if(a==0){
                throw new BusinessRuntimeException(ResultCodeEnum.UPDATE_FAIL.getCode(),ResultCodeEnum.UPDATE_FAIL.getMessage());
            }
            return ResponseResult.ok(a);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult updatePatent(Patent patent) {
        try {
            if(ObjectUtils.isEmpty(patent)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            int a = patentMapper.updateByPrimaryKeySelective(patent);
            if(a==0){
                throw new BusinessRuntimeException(ResultCodeEnum.UPDATE_FAIL.getCode(),ResultCodeEnum.UPDATE_FAIL.getMessage());
            }
            return ResponseResult.ok(a);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult getSix(Integer userId) {
        SixSigma sigma =null;
        try {
            if(ObjectUtils.isEmpty(userId)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            sigma = sigmaMapper.getSixSigma(userId);
            return ResponseResult.ok(sigma);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult updateSix(SixSigma sigma) {
        try {
            if(ObjectUtils.isEmpty(sigma)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            Integer id = sigma.getId();
            int a =0;
            if(ObjectUtils.isEmpty(id)){
                a = sigmaMapper.insertSelective(sigma);
                if(a==0){
                    throw new BusinessRuntimeException(ResultCodeEnum.ADD_FAILE.getCode(),ResultCodeEnum.ADD_FAILE.getMessage());
                }
            }else {
                 a=sigmaMapper.updateByPrimaryKeySelective(sigma);
                if(a==0){
                    throw new BusinessRuntimeException(ResultCodeEnum.UPDATE_FAIL.getCode(),ResultCodeEnum.UPDATE_FAIL.getMessage());
                }

            }
            return ResponseResult.ok(a);

        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    private Archives getDetails(Integer id){
        Archives archives=new Archives();
        User user = userMapper.selectByPrimaryKey(id);
        if(ObjectUtils.isEmpty(user)){
            return archives;
        }
        Integer rankId = user.getRankId();
        Integer deptId = user.getDeptId();
        Integer eduId = user.getEduId();
        BeanUtils.copyProperties(user,archives);
        if(deptId!=null){
            Deptment deptment = archivesMapper.getDeptment(deptId);
            if(!ObjectUtils.isEmpty(deptment)){
                BeanUtils.copyProperties(deptment,archives);
            }
        }

        if(rankId!=null){
            Rank rank = archivesMapper.getRank(rankId);
            if(!ObjectUtils.isEmpty(rank)){
                BeanUtils.copyProperties(rank,archives);
            }
        }
        JobTitle titleInfo = archivesMapper.getTitleInfo(id);
        if(!ObjectUtils.isEmpty(titleInfo)){
            BeanUtils.copyProperties(titleInfo,archives);
        }
        String s = null;
        if(user.getRankUpdate()!=null){
            Date rankUpdate = user.getRankUpdate();
            s = TimeUtil.yearCompare(rankUpdate);
        }
        if(user.getUsername()!=null){
            archives.setUserName(user.getUsername());
        }
        if(user.getJob()!=null){
            archives.setJob(user.getJob());
        }
        if(eduId!=null){
            Eduu eduu = archivesMapper.getEdu(eduId);
            archives.setEduId(eduId);
            if(!ObjectUtils.isEmpty(eduu)){
                BeanUtils.copyProperties(eduu,archives);
                if(!ObjectUtils.isEmpty(eduu.getEduMajor())){
                    archives.setMajor(eduu.getEduMajor());
                }
            }
        }
        archives.setDetentionTime(s);
        return archives;
    }

    private Map getTimes(Integer id){
        Integer timeClass=0;
        Integer timeAttendance=0;
        Map<String,Integer> map=new HashMap<>();
        List<Integer> classTime = archivesMapper.getClassTime(id);
        List<Integer> attendanceTime = archivesMapper.getAttendanceTime(id);
        if(!CollectionUtils.isEmpty(classTime)){
            for (Integer c : classTime) {
                if(ObjectUtils.isEmpty(c)){
                    continue;
                }
                timeClass +=c;
            }
        }
        if(!CollectionUtils.isEmpty(attendanceTime)){
            for (Integer a : attendanceTime) {
                if(ObjectUtils.isEmpty(a)){
                    continue;
                }
                timeAttendance +=a;
            }
        }
        map.put("classTime",timeClass);
        map.put("attendanceTime",timeAttendance);
        return map;
    }

    public static List<String> sortList(List<String> list){
        for (int i = 0; i< list.size();i++){
            int length = list.get(i).toString().length();
            for (int j = i + 1; j <= list.size()-1;j++){
                int length1 = list.get(j).toString().length();
                if (length < length1){
                    String s = list.get(i).toString();
                    list.set(i,s);
                }else {
                    String s = list.get(i).toString();
                    String s1 = list.get(j).toString();
                    list.set(i,s1);
                    list.set(j,s);
                }
            }
        }
        return list;
    }
}